package app.beit.finportal.controller.backdoor;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.List;

import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import app.beit.finportal.bean.AccountBean;
import app.beit.finportal.controller.BaseController;
import app.beit.finportal.controller.FintrackResponse;
import app.beit.finportal.service.AccountService;
import app.beit.finportal.utils.FinportalEncryption;
import app.beit.finportal.utils.constr.MsgConstr;
import app.beit.finportal.utils.constr.SessionConstr;

@Controller
@RequestMapping("/backend")
public class LoginController extends BaseController {

	@Autowired
	private AccountService accountService;
	
	@RequestMapping
	public String main(){
		return "backend.main";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="checkUser", method=RequestMethod.POST)
	@ResponseBody
	public FintrackResponse<AccountBean> checkUser(final HttpServletRequest request, final @RequestParam(value="username") String username, 
			final @RequestParam(value="password") String password){
		FintrackResponse<AccountBean> response = null;
		String pass = "";
		try {
			pass = FinportalEncryption.getInstance().encrypt(password);
		} catch (InvalidKeyException | InvalidAlgorithmParameterException
				| InvalidKeySpecException | NoSuchAlgorithmException
				| NoSuchPaddingException e1) {
			e1.printStackTrace();
		}
		try{
			final List<AccountBean> beans = this.accountService.getAccount(username, pass);
			if(beans != null && beans.size() > 0){
				final AccountBean bean = beans.get(0);
				if(bean.getStatus() == 0){
					return super.responseError(MsgConstr.USERNAME_IS_INACTIVE_CODE, MsgConstr.USERNAME_IS_INACTIVE_MSG);
				}
				bean.setPassword(FinportalEncryption.getInstance().decrypt(bean.getPassword()));
				response = super.responseSuccess();
				response.setDatas(bean);
				request.getSession().setAttribute(SessionConstr.USER, bean);
			}else{
				response = super.responseError(MsgConstr.USERNAME_IS_INCORRECT_CODE, MsgConstr.USERNAME_IS_INCORRECT_MSG);
			}
		}catch(Exception e){
			e.printStackTrace();
			response = super.responseError("E0001", e.getMessage());
		}
		
		return response;
	}
}
